<template>
    <div>
      <div id="main" style="width: 100%; height: 290px;"></div>
    </div>
  </template>
  
  <script>
  import * as echarts from 'echarts';
  import axios from 'axios';
  
  export default {
    data() {
      return {
        createTimes: [],
      };
    },
  
    methods: {
      async getLoginMonth() {
        try {
          const { data: res } = await axios.get(`users/getLoginMonth`);
          this.createTimes = res.map((user) => user.createtime);
          this.initChart();
        } catch (error) {
          console.error(error);
          this.$message.error("请求失败: " + error.message);
        }
      },
      initChart() {
        // 初始化图表
        const chartDom = document.getElementById('main');
        const myChart = echarts.init(chartDom);
  
        // 处理数据
        const dateCounts = {};
        this.createTimes.forEach(ctime => {
          const date = new Date(ctime).getDate();
          if (dateCounts[date]) {
            dateCounts[date]++;
          } else {
            dateCounts[date] = 1;
          }
        });
  
        // 准备图表数据
        const dates = Array.from({ length: 31 }, (_, i) => i + 1);
        const counts = dates.map(date => dateCounts[date] || 0);
  
        // 配置图表
        const option = {
          title: {
            text: '用户当月访问情况'
          },
          tooltip: {
            trigger: 'axis'
          },
          toolbox: {
            feature: {
              saveAsImage: {},
              dataView: { readOnly: false },
              magicType: { type: ['line', 'bar'] },
              restore: {},
              dataZoom: {}
            }
          },
          xAxis: {
            type: 'category',
            data: dates,
            name: '日期'
          },
          yAxis: {
            type: 'value',
            name: '访问次数'
          },
          series: [
            {
              name: '用户访问量',
              type: 'line',
              data: counts
            }
          ]
        };
  
        // 设置图表选项
        myChart.setOption(option);
      }
    },
  
    mounted() {
      this.getLoginMonth();
    }
  };
  </script>
  
  <style scoped>
  /* 您可以在这里添加样式 */
  </style>